package jrdesktop.viewer.main.FileMng;

import jrdesktop.viewer.main.*;
import java.io.File;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import jrdesktop.utilities.FileUtility;

/**
 * FileTransGui.java
 * @author  benbac
 */

public class FileTransGui extends javax.swing.JFrame {
    private Recorder recorder;
        
    private boolean canceled = false;
    private boolean done = false;
    
    private File[] files;
    private long index = 0;    
    private long count = 0;
    private long size = 0;
    private long startedAt = 0;
    private long duration = 0;
    private long speed = 0;    
    private float leftEstim = 0.0f;
    private float totalEstim = 0.0f;   
    
    /** Creates new form FileTransGui */
    public FileTransGui(Recorder recorder) {
        this.recorder = recorder;
        initComponents();
        setVisible(true);
        startedAt = System.currentTimeMillis();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jProgressBar1 = new javax.swing.JProgressBar();
        jLabel1 = new javax.swing.JLabel();
        jLabelCurrentFile = new javax.swing.JLabel();
        jLabelFileCount = new javax.swing.JLabel();
        jLabelTotalSize = new javax.swing.JLabel();
        jLabelSpeed = new javax.swing.JLabel();
        jLabelDuration = new javax.swing.JLabel();
        jButtonClose = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("jrdesktop - File Transmission");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jProgressBar1.setMaximumSize(new java.awt.Dimension(150, 20));
        jProgressBar1.setMinimumSize(new java.awt.Dimension(150, 20));
        jProgressBar1.setPreferredSize(new java.awt.Dimension(150, 20));
        jProgressBar1.setStringPainted(true);

        jLabel1.setText("Current file:");

        jLabelFileCount.setText("0 file(s)");

        jLabelTotalSize.setText("0 KB");

        jLabelSpeed.setText("0 KB/S");

        jLabelDuration.setText("0 Seconds");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelCurrentFile)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 436, Short.MAX_VALUE)
                        .addComponent(jLabelFileCount))
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 536, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabelDuration)
                        .addGap(220, 220, 220)
                        .addComponent(jLabelSpeed)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 215, Short.MAX_VALUE)
                        .addComponent(jLabelTotalSize)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabelCurrentFile)
                    .addComponent(jLabelFileCount))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelTotalSize)
                    .addComponent(jLabelDuration)
                    .addComponent(jLabelSpeed))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButtonClose.setText("Cancel");
        jButtonClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCloseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonClose, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButtonClose)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-600)/2, (screenSize.height-170)/2, 600, 170);
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCloseActionPerformed
        if (done) dispose();
        else if (JOptionPane.showConfirmDialog(this, 
               "Stop file transmission ?", "Confirm Dialog", 
               JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE)
               == JOptionPane.OK_OPTION) {       
                canceled = true;      
                dispose();
            }
}//GEN-LAST:event_jButtonCloseActionPerformed
    
    /**
     * @param args the command line arguments
     */
   /* public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FileTransGui().setVisible(true);
            }
        });
    }*/    
   
    private SwingWorker sendingWorker = new SwingWorker() {
        @Override
        protected Object doInBackground() throws Exception {              
            recorder.fileManager.SendFiles(FileTransGui.this, files);                 
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        protected void done() {
            Done();
        }      
    };
        
    private SwingWorker receivingWorker = new SwingWorker() {
        @Override
        protected Object doInBackground() throws Exception {        
            recorder.fileManager.ReceiveFiles(FileTransGui.this, files); 
            throw new UnsupportedOperationException("Not supported yet.");
        }
            
        @Override
        protected void done() {
            Done();
        }             
   };
       
   public boolean isCanceled () {
        return canceled;
   }   
   
   public void Done() {
        done = true;
        jButtonClose.setText("Close");
        setTitle("jrdesktop - File Transmission [Done !! ]");       
   }
   
   public void ReceiveFiles (ArrayList arrayList) {
        setTitle("jrdesktop - File Transmission [Receiving ...]");       
        recorder.fileManager.setServerDownloadingFolder(
                arrayList.get(0).toString());
        recorder.fileManager.setDownloadingFolder(
                FileUtility.getCurrentDirectory());
        files = (File[]) arrayList.get(1);
        count = files.length;        
        
        receivingWorker.execute();          
   }   
   
   public void SendFiles (File[] _files) {       
       setTitle("jrdesktop - File Transmission [Sending ...]");               
       recorder.fileManager.setUploadingFolder(
               _files[0].getParent() + File.separatorChar);        
       files = FileUtility.getAllFiles(_files); 
       count = files.length; 
       
       sendingWorker.execute();       
   }
   
   public void setCurrentFile(String filename) {
        jLabelCurrentFile.setText(filename);    
   }   

   public void updateData(long size) {
       this.size = size;
       index ++;
       duration = System.currentTimeMillis() - startedAt;
       speed = size / (duration + 1);
       leftEstim = (float) duration / (float) index;
       totalEstim = leftEstim * (float) count;
       
        jLabelFileCount.setText(String.valueOf(index) + "/" 
               + String.valueOf(count) + " file(s)");         
       jLabelTotalSize.setText(String.valueOf(size / 1000) + " KB");       
       jLabelDuration.setText(String.valueOf(duration / 1000) + " Seconds");
       jLabelSpeed.setText(String.valueOf(speed) + " KB/S");
       jProgressBar1.setMaximum((int) totalEstim);
       jProgressBar1.setValue((int) (leftEstim * index));
   }   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonClose;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabelCurrentFile;
    private javax.swing.JLabel jLabelDuration;
    private javax.swing.JLabel jLabelFileCount;
    private javax.swing.JLabel jLabelSpeed;
    private javax.swing.JLabel jLabelTotalSize;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JProgressBar jProgressBar1;
    // End of variables declaration//GEN-END:variables
    
}
